package com.zac.pomodoro.ui.theme

import android.os.CountDownTimer

class PausableCountDownTimer(
    private val millisInFuture: Long,
    private val countDownInterval: Long,
    private val onTick1: (Long) -> Unit,
    private val onFinish1: () -> Unit
) {
    private var initTime = millisInFuture
    private var remainingTime = millisInFuture
    private var timer: CountDownTimer? = null
    var isPaused = true
        private set

    fun start() {
        if (timer != null) return

        timer = object : CountDownTimer(remainingTime, countDownInterval) {
            override fun onTick(millisUntilFinished: Long) {
                if (!isPaused) {
                    remainingTime = millisUntilFinished
                    onTick1(millisUntilFinished)
                }
            }

            override fun onFinish() {
                if (!isPaused) onFinish1()
            }
        }.start()
    }

    fun pause() {
        isPaused = true
        timer?.cancel()
        timer = null
    }

    fun resume() {
        isPaused = false
        start()
    }

    fun cancel() {
        timer?.cancel()
        isPaused = true
        remainingTime = initTime
        timer = null
    }
}